<?php

namespace App\Model;

use PhalApi\Model\DataModel;



class IdcardUnitPreson extends DataModel
{
    //对单位人员进行排序
    public $tableName = 'phalapi_user_by_unit_order';
    protected function getTableName($id)
    {
        return $this->tableName;
    }

    public function UpdateInfo($data)
    {
        //更新个人信息
        $id = $data->id;
        $arr = $data->arr;
        // 对数据进行还原
        $arr = json_decode($arr,true);
        $arr['update_time'] = date("Y-m-d H:i:s",time());
        //如果传了id 就对id就行更新
        if ( $id ){
            // 对该id进行更新
            $this->tableName = 'phalapi_user';
            $this->getORM()->where("id", $id)->update($arr);
            return $this->order_personnel($arr);
        }
    }


    //存入数据
    public function order_personnel($data)
    {
        //重构新数组
        $new_data = array();
        foreach ($data as $k => $v){
            if ($v){
                $new_data[$k]=$v;
            }
        }

        $username = $new_data['username'];
        $unit = $new_data['unit'];

        $this->tableName = 'phalapi_user_by_unit_order';
        if( $unit && $username){
            $orderInfo = $this->getORM()->select('*')->where(array("username"=>$username,'unit'=>$unit ))->fetchOne();
            //如果没有该员工, 测创建序号
            if (!$orderInfo){
                $unit_number = $this->getORM()->where('unit', $unit)->count("id");
                $saveData = array(
                    'username' => $username,
                    'unit' => $unit,
                    'unit_times' => $unit_number + 1,
                    'update_time' => date("Y-m-d H:i:s", time()),
                    'create_time' => date("Y-m-d H:i:s", time()),
                );
                $unit_personnel = $this->getORM()->insert($saveData);
                return $this->update_format($unit_personnel);
            }
        }
    }

    public function update_format($data)
    {
        //把数据更新到 phalapi_user
        function setStart($n){
            $A = array();
            for($i=65;$i<91;$i++){
                $A[]=strtoupper(chr($i));//输出大写字母
            }
            // print_r($A);
            if ($n <= 26){
                return $A[$n%26];
            }else{
                return setStart(intval($n/26)) . setStart($n%26);
            }
        }

        $this->tableName = 'phalapi_user';
        $n = $data['unit_times']-1;
        $username = $data['username'];
        $this->getORM()->where('username', $username)->update(array( 'water_order' => setStart($n) ));
        return setStart($n);
    }


}
